package com.miage.itrading.server.business;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;

import com.miage.itrading.server.dao.CotationDAO;
import com.miage.itrading.server.dao.SGBDDao;
import com.miage.itrading.shared.entites.Cotation;

public class Historique extends Thread {

	public void run() {
		Calendar calDebut = Calendar.getInstance();
		Calendar calFin = Calendar.getInstance();

		calFin.add(Calendar.DAY_OF_MONTH, -1);

		calFin.set(Calendar.HOUR, 0);
		calFin.set(Calendar.MINUTE, 0);
		calFin.set(Calendar.SECOND, 0);

		try {
			SGBDDao s = new SGBDDao();

			ArrayList<Cotation> cotations = (ArrayList<Cotation>) (s
					.getCotations());

			java.util.Date derniereCotation;

			for (int i = 0; i < cotations.size(); ++i) {

				derniereCotation = s.getDateDerniereValeur(cotations.get(i)
						.getIdCotation());

				if (derniereCotation == null) {
					calDebut.set(1990, 1, 1);
					calDebut.add(Calendar.MONTH, -1);

				} else {
					calDebut.setTime(derniereCotation);
					calDebut.add(Calendar.DAY_OF_MONTH, 1);
				}
				calDebut.set(Calendar.HOUR, 0);
				calDebut.set(Calendar.MINUTE, 0);
				calDebut.set(Calendar.SECOND, 0);

				if (calDebut.getTime().before(calFin.getTime())) {
					CotationDAO daocotation;
					try {
						daocotation = new CotationDAO(
								cotations.get(i).getNom(), cotations.get(i)
										.getMnemonique());

						new StockQuoter(daocotation, calDebut
								.get(Calendar.DAY_OF_MONTH), calDebut
								.get(Calendar.MONTH), calDebut
								.get(Calendar.YEAR), calFin
								.get(Calendar.DAY_OF_MONTH), calFin
								.get(Calendar.MONTH), calFin.get(Calendar.YEAR));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

		} catch (SQLException e2) {
			e2.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
